﻿using DevExpress.XtraEditors;
using DevExpress.XtraTab;
using EkStudio.com.bean.xml.BillMapping;
using EkStudio.com.bean.xml.reflection.JAXB;
using EkStudio.com.bean.xml.RootInterface.Plugin;
using EkStudio.com.bean.xml.Unit;
using EkStudio.com.common.unit;
using EkStudio.com.ui.form.MapDataSource;
using EkStudio.com.ui.unitbill.property;
using EkStudio.Com.UI.Interface;
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Xml;

namespace EkStudio.com.ui.unitbill
{
    public partial class BillMapUnitPanel : XtraUserControl, ProjectUnitBillInterface
    {
        private log4net.ILog logger = log4net.LogManager.GetLogger(typeof(BillMapUnitPanel));

        private bool readOnly = false;
        private bool save = true;
        private ProjectRootPanel RootPanel = null;
        private ProjectUnitBillInterface ParentUnit = null;
        private List<ProjectUnitBillInterface> SubjectUnit = new List<ProjectUnitBillInterface>();//子面板

        private BillDataMapGroupItem selectItem = null;

        //配置属性
        private BillDataMapItem Map = null;

        private BillMapToProperty MapProperty = null;



        public BillMapUnitPanel(ProjectRootPanel root,BillDataMapItem bean,bool read)
        {
            InitializeComponent();
            RootPanel = root;
            Map = bean;
            readOnly = read;
            InitUnitPanel();
        }
        private void InitUnitPanel()
        {
            RepositoryMonthTypeList.Items.AddRange(BeanUtil.STOCK_SAVE_TYPE);

            MapProperty = new BillMapToProperty(Map);
            ModPropertyGridControl.SelectedObject = MapProperty;

            DataMapView.Items.Clear();
            DataPluginView.Items.Clear();
            //初始化数据映射列表
            if (Map.GroupProperties == null) Map.GroupProperties = new BillDataMapGroupRoot();
            if (Map.GroupProperties.FieldsProperties == null) Map.GroupProperties.FieldsProperties = new List<BillDataMapGroupItem>();
            if (Map.GroupProperties.FieldsProperties.Count > 0)
            {
                for(int i = 0; i < Map.GroupProperties.FieldsProperties.Count; i++)
                {
                    BillDataMapGroupItem group = Map.GroupProperties.FieldsProperties[i];
                    ListViewItem it = new ListViewItem(group.Caption, 0);
                    it.Name = group.Key;
                    it.Tag = group;
                    DataMapView.Items.Add(it);
                }
            }
            //初始化扩展代码列表
            if (Map.ExpandProperties == null) Map.ExpandProperties = new BillExpandJavaCodeRoot();
            if (Map.ExpandProperties.JavaItem == null) Map.ExpandProperties.JavaItem = new List<BillExpandJavaCodeItem>();
            if (Map.ExpandProperties.JavaItem.Count > 0)
            {
                for(int i = 0; i < Map.ExpandProperties.JavaItem.Count; i++)
                {
                    BillExpandJavaCodeItem java = Map.ExpandProperties.JavaItem[i];
                    ListViewItem it = new ListViewItem(java.Caption, 1);
                    it.Name = java.Key;
                    it.Tag = java;
                    DataPluginView.Items.Add(it);
                }
            }
        }


        #region 接口功能实现

        public string BillKey
        {
            get { return Map.MapProperties.Key; }
        }

        public bool ReadOnly
        {
            get { return readOnly; }
            set { readOnly = value; }
        }

        public bool isSubUnitBill
        {
            get { return false; }
        }

        public ProjectUnitBillInterface ParentPage
        {
            get { return ParentUnit; }
            set { ParentUnit = value; }
        }

        public List<ProjectUnitBillInterface> SubjectPage
        {
            get { return SubjectUnit; }
        }

        public bool SaveStatus
        {
            get { return save; }
            set { save = value;RootPanel.SaveStatus = value; }
        }

        

        public void AddSubjectBill(ProjectUnitBillInterface bill)
        {
            
        }

        public void RemoveSubjectBill(ProjectUnitBillInterface bill)
        {

        }

        public bool ContainSubject(ProjectUnitBillInterface bill)
        {
            return false;
        }

        public void saveData(bool updateParent)
        {
            if (!readOnly && (!save || !isSubSaveStatus()))
            {
                if (!isSubSaveStatus())
                {
                    //先保存子表
                    foreach (ProjectUnitBillInterface subPage in SubjectUnit)
                    {
                        subPage.saveData(false);
                    }
                }
                Map.MapProperties.RootVersion = BeanUtil.VERSION;
                Map.MapProperties.Owner.LastMender = RootPanel.UserInfo.UserName;
                Map.MapProperties.Owner.LastModified = StringUtility.getZwStandLongDate();
                JAXBContext<BillDataMapItem> jaxb = new JAXBContext<BillDataMapItem>();

                string xml = jaxb.marshal(Map, !Map.MapProperties.Compress);

                string result = RootPanel.Http.SaveXmlBean(Map.getKey(), ProjectUtil.TYPE_BILL_DATAMAP, xml);
                XmlDocument docXml = new XmlDocument();
                try
                {
                    docXml.LoadXml(result);
                    XmlElement root = docXml.DocumentElement;
                    XmlNode node = root.SelectSingleNode("result");
                    if (node.InnerText == "0")
                    {
                        RootPanel.AddConsoleText(string.Format("保存模块[{0}]成功", Map.getCaption()), false);
                    }
                    else
                    {
                        RootPanel.AddConsoleText(string.Format("保存模块[{0}]失败", Map.getCaption()), false);
                    }
                }
                catch (Exception e)
                {
                    RootPanel.AddConsoleText(string.Format("保存模块[{0}]失败,请检查网络连接", Map.getCaption()), false);
                    logger.Error("保存失败", e);
                }
                save = true;
                if (updateParent) RootPanel.SaveStatus = true;
            }
        }

        /// <summary>
        /// 复制
        /// </summary>
        /// <param name="clazz">复制后的clazz</param>
        /// <returns></returns>
        public bool Copy(out object clazz)
        {
            bool val = false;
            clazz = null;

            return val;
        }

        public bool close()
        {
            bool result = true;
            if (!save || !this.isSubSaveStatus())
            {
                DialogResult dialog = XtraMessageBox.Show("当前数据已更改是否保存?", "提示", MessageBoxButtons.YesNoCancel);
                if (dialog == DialogResult.Yes)
                {
                    this.saveData(true);
                    result = true;
                }
                else if (dialog == DialogResult.No)
                {
                    result = true;
                }
                else
                {
                    result = false;
                }
            }

            if (result)
            {
                //释放模块占用
                try
                {
                    RootPanel.Http.ReleaseModule(Map.getKey(), Map.getCaption(), ProjectUtil.TYPE_BILL_DATAMAP);
                }
                catch (Exception e)
                {
                    this.RootPanel.AddConsoleText("页面关闭失败", true);
                    logger.Error("页面关闭失败", e);
                }

            }

            return result;
        }

        #endregion

        /// <summary>
        /// 子页面保存状态
        /// </summary>
        /// <returns></returns>
        private bool isSubSaveStatus()
        {
            bool result = true;
            if (SubjectUnit.Count > 0)
            {
                for (int i = 0; i < SubjectUnit.Count; i++)
                {
                    if (!SubjectUnit[i].SaveStatus)
                    {
                        result = false;
                        break;
                    }
                }
            }

            return result;
        }


        #region 事件注册

        /// <summary>
        /// Tab切换事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TabControlPanel_SelectedPageChanged(object sender, DevExpress.XtraTab.TabPageChangedEventArgs e)
        {
            //if (TabControlPanel.SelectedTabPageIndex >= 0)
            //{
            //    XtraTabPage page = TabControlPanel.SelectedTabPage;
            //    if (page.Controls.Count > 0 && page.Controls[0] is ListView)
            //    {
            //        ListView view = (ListView)page.Controls[0];
            //        view.ContextMenuStrip = FieldPopMenu;
            //    }
            //}
        }
        /// <summary>
        /// 新建字段
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FieldPopNewNode_Click(object sender, EventArgs e)
        {
            BillDataMapGroupItem it = new BillDataMapGroupItem();
            Map.GroupProperties.addNode(it,Map);
            ListViewItem view = new ListViewItem(it.Caption, 0);
            view.Tag = it;
            DataMapView.Items.Add(view);
            view.Selected = true;
            SaveStatus = false;

        }
        /// <summary>
        /// 删除字段
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FieldPopDeleteNode_Click(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// 仓库对象选择功能执行
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void RepositoryStockClassEdit_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if (classForm == null) classForm = new MapStockClassForm(RootPanel, this, Map);
            if(classForm.ShowDialog() == DialogResult.OK)
            {
                SaveStatus = false;
                ModPropertyGridControl.Refresh();
            }
        }


        /// <summary>
        /// 模块属性值改变触发事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ModPropertyGridControl_CellValueChanged(object sender, DevExpress.XtraVerticalGrid.Events.CellValueChangedEventArgs e)
        {
            if(e.Row.Properties.FieldName == "RunTimer")
            {
                RootPanel.AddConsoleText(Map.MapProperties.RunTimer, false);
                DateTime time = (DateTime)e.Value;
                Map.MapProperties.RunTimer = time.ToString("HH:mm:ss");
                Map.MapProperties.Balance = string.Format("每月第{0}天的[{1}]执行", Map.MapProperties.IndexDay, Map.MapProperties.RunTimer);
                ModPropertyGridControl.Refresh();
            }
            else if(e.Row.Properties.FieldName == "IndexDay")
            {
                Map.MapProperties.Balance = string.Format("每月第{0}天的[{1}]执行",Map.MapProperties.IndexDay,Map.MapProperties.RunTimer);
                ModPropertyGridControl.Refresh();
            }

            SaveStatus = false;
        }
        /// <summary>
        /// 库存计算集设置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void RepositoryTargetEdit_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if (targetForm == null) targetForm = new MapTargetForm(RootPanel, this, Map);
            if(targetForm.ShowDialog() == DialogResult.OK)
            {
                SaveStatus = false;
                ModPropertyGridControl.Refresh();
            }
        }
        //分组属性值变更
        private void GroupGridControl_CellValueChanged(object sender, DevExpress.XtraVerticalGrid.Events.CellValueChangedEventArgs e)
        {
            if(e.Row.Properties.FieldName == "Caption")
            {
                ListViewItem it = DataMapView.SelectedItems[0];
                it.Text = (string)e.Value;
            }
            SaveStatus = false;
        }
        /// <summary>
        /// 选择项变更执行事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DataMapView_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (DataMapView.SelectedItems.Count > 0)
            {
                ListViewItem it = DataMapView.SelectedItems[0];
                if(it.Tag is BillDataMapGroupItem)
                {
                    selectItem = it.Tag as BillDataMapGroupItem;
                    BillMapUiGroupToProperty group = new BillMapUiGroupToProperty(selectItem);
                    GroupGridControl.SelectedObject = group;
                    GroupGridControl.Visible = true;
                }
            }
        }


        private void DataMapView_Click(object sender, EventArgs e)
        {
            DataMapView_SelectedIndexChanged(sender, e);
        }
        /// <summary>
        /// 分组影射设置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void RepositoryMappingCfgEdit_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            MapGroupClassForm groupForm = new MapGroupClassForm(RootPanel, this, Map);
            groupForm.Group = selectItem;
            if(groupForm.ShowDialog() == DialogResult.OK)
            {
                SaveStatus = false;
                GroupGridControl.Refresh();
            }
        }

        #endregion



        private MapTargetForm targetForm = null;
        private MapStockClassForm classForm = null;

        
    }
}
